<template>
  <div :ref="info._id" v-ui-ref="vSetRef" class="w-full overflow-auto h-full">
    <!-- 头部图例区域 -->
    <div class="flex min-w-[320px] flex-wrap">
      <div v-for="(item, index) in getExtension.legend.value" :key="index" class="flex items-center">
        <p
          class="rounded-sm"
          :style="{
            width: '30px',
            height: '15px',
            background: item.color,
          }"
        ></p>
        <p class="ml-1 mr-3">{{ item.legendName }}</p>
      </div>
    </div>
    <!-- 内容区域 -->
    <div class="mt-6 flex items-center min-w-[320px]" :class="isHorizontalModel ? '' : 'flex-col'">
      <div v-if="!dataList.length">{{ translateTitle('Ve.elements.暂无数据') }}!</div>
      <div v-for="(item, index) in dataList" :key="index" class="flex" :class="isHorizontalModel ? 'flex-col flex-none w-[220px]' : 'w-[320px]'">
        <div class="flex items-center" :class="isHorizontalModel ? 'mb-2' : 'flex-col mr-4'" @dblclick="handlerDbclick(item)">
          <span
            class="w-[100px] h-[40px] text-center leading-[40px] truncate cursor-pointer px-2.5"
            :class="index === 0 || index === dataList.length - 1 ? 'rounded-[100%]' : 'rounded-md'"
            :style="{ background: getBackGroundColor(item[statusField]), color: titleColor, fontSize: '12px', fontWeight: 600 }"
            :title="item[titleField]"
          >
            {{ item[titleField] }}
          </span>
          <span v-if="index !== dataList.length - 1 && !isHorizontalModel" class="h-10 border-l-4 border-gray-500"></span>
          <span v-if="index !== dataList.length - 1 && isHorizontalModel" class="w-[120px] border-b-4 border-gray-500"></span>
        </div>
        <div class="h-[50px] flex flex-col justify-between" :style="{ fontSize: '13px' }">
          <p v-if="item[startTimeField]">
            <span>{{ translateTitle('Ve.elements.开始时间') }}：</span>
            <span>{{ item[startTimeField] }}</span>
          </p>
          <p v-if="item[endTimeField]">
            <span>{{ translateTitle('Ve.elements.结束时间') }}：</span>
            <span>{{ item[endTimeField] }}</span>
          </p>
          <p v-if="item[startTimeField] && item[endTimeField]">
            <span>{{ translateTitle('Ve.elements.执行时间') }}：</span>
            <span>{{ getExecutionTime(item[startTimeField], item[endTimeField]) }}</span>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
  import { translateTitle } from '@/utils/i18n'
  import { defineComponent } from 'vue'
  import { UiMixin, RefsInjectMixin } from '@ve/mixin'
  import { domHeight } from '@ve/utils/domHeight'
  import request from '@/utils/request'
  import { GFCD } from '@/utils/utils'
  import isEmpty from 'lodash/isEmpty'
  import isArray from 'lodash/isArray'
  import trim from 'lodash/trim'
  import { processingConstant, replaseRegVariable } from '@ve/utils/utils'
  import dayjs from 'dayjs'

  export default defineComponent({
    name: 'UiFlowChart',
    components: {},
    mixins: [UiMixin, RefsInjectMixin],

    data() {
      return {
        domHeight: 100,
        interval: null,
        // dataList: [
        //   {
        //     title: '触发站点',
        //     startTime: '2022-09-09 23:12:08',
        //     endTime: '2022-09-09 23:12:08',
        //     status: '1',
        //   },
        //   {
        //     title: '站点1',
        //     startTime: '2022-09-09 23:12:08',
        //     endTime: '2022-09-09 23:12:08',
        //     status: '1',
        //   },
        //   {
        //     title: '站点2',
        //     startTime: '2022-09-09 23:12:08',
        //     endTime: '2022-09-09 23:12:08',
        //     status: '4',
        //   },
        //   {
        //     title: '站点3',
        //     startTime: '2022-09-09 23:12:08',
        //     endTime: '',
        //     status: '2',
        //   },
        //   {
        //     title: '站点4',
        //     startTime: '',
        //     endTime: '',
        //     status: '3',
        //   },
        //   {
        //     title: '结束站点',
        //     startTime: '',
        //     endTime: '',
        //     status: '3',
        //   },
        // ],
      }
    },
    computed: {
      getExtension() {
        return this.info.extension
      },
      dataList() {
        return this.info.data.requestData.data || []
      },
      titleField() {
        return this.info.extension.titleField.value
      },
      startTimeField() {
        return this.info.extension.startTimeField.value
      },
      endTimeField() {
        return this.info.extension.endTimeField.value
      },
      statusField() {
        return this.info.extension.statusField.value
      },
      titleColor() {
        if (this.info.extension.titleColor && this.info.extension.titleColor.value) {
          return this.info.extension.titleColor.value
        } else {
          return '#000'
        }
      },
      isHorizontalModel() {
        return this.info.extension.horizontalModel && this.info.extension.horizontalModel.value
      },
    },
    created() {
      // 计算高度
      this.getHeight()
      this.$sub(`SplitpaneResized_${this.previewPageId()}`, () => {
        this.getHeight()
      })
    },
    mounted() {
      // console.log(this.info)
      if (!this.getHasPreview) {
        return
      } else {
        // 调用接口
        if (this.getInfo.extension.api.value) this.requestData()
      }
    },
    unmounted() {
      // 取消定时器
      if (this.interval) {
        clearInterval(this.interval)
      }
    },
    methods: {
      translateTitle,
      getBackGroundColor(status) {
        let color = ''
        this.getExtension.legend.value.forEach((item) => {
          // 如果值里面有 ，则代表为多指匹配同一个图例
          if (item.legendValue.indexOf(',') > -1) {
            let legendValueList = item.legendValue.split(',')
            legendValueList.forEach((legendValueItem) => {
              if (trim(legendValueItem) === status) {
                color = item.color
              }
            })
          } else {
            if (item.legendValue === status) {
              color = item.color
            }
          }
        })
        return color
      },
      getHeight() {
        let _domHeight = domHeight(this)
        if (_domHeight > 0) {
          this.domHeight = _domHeight
        }
      },
      requestData(cb) {
        let requestDataObj = {}
        isArray(this.info.extension.requestData.value) &&
          this.info.extension.requestData.value.forEach((item) => {
            let itemVal = item.value
            if (/#{.*?}/g.test(item.value)) {
              itemVal = replaseRegVariable(itemVal, this.info.data.formData)
            }
            requestDataObj[item.key] = processingConstant(this, itemVal)
          })
        let options = {
          api: this.info.extension.api.value,
          method: this.info.extension.method.value,
          getDataKey: this.info.extension.getDataKey.value,
          data: { ...this.info.data.formData, ...requestDataObj },
        }
        if (!trim(options.api)) return
        if (this.info.extension.loopTime && this.info.extension.loopTime.value) {
          // 如果有配置循环间隔 则循环调用接口
          if (this.interval) {
            clearInterval(this.interval)
          }
          this.interval = setInterval(() => {
            this.request(options)
          }, this.info.extension.loopTime.value)
        }
        this.request(options, cb)
      },
      // 统一请求
      request(options = {}, cb) {
        this.loading = true
        let getDataKey = this.getExtension.getDataKey.value
        //发起请求
        return request({
          url: GFCD('dams', 'domain') + options.api,
          method: 'post',
          data: {
            data: JSON.stringify(options.data),
            method: options.method,
          },
        }).then((res) => {
          this.loading = false
          //解密
          // console.log(decryptd(res))
          // let _requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          // if (isArray(_requestData)) {
          //   this.getInfo.data.requestData = _requestData
          // } else {
          //   this.getInfo.data.requestData = []
          // }
          this.getInfo.data.requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
          // 回调
          cb && cb(res)
        })
      },
      handlerDbclick(data) {
        this.runEventTask('onDbClick', {
          data,
        })
      },
      $requestData(cb) {
        this.requestData(cb)
      },
      // 获取执行时间
      getExecutionTime(start, end) {
        console.log(dayjs(end).diff(start, 'm'))
        // console.log(dayjs().(dayjs(end).diff(start, 'm')))
        const timeDiff = dayjs(end).diff(start, 'm')
        if (!timeDiff) {
          // 如果运行时间少于一分钟 则取秒数
          return `${dayjs(end).diff(start, 's')}${translateTitle('Ve.elements.秒')}`
        }
        const hNum = Math.floor(timeDiff / 60)
        const mNum = timeDiff % 60
        if (!hNum) {
          // 不足一小时的话则不显示小时
          return `${mNum}${translateTitle('Ve.elements.分')}`
        }
        return `${hNum}${translateTitle('Ve.elements.小时')}${mNum}${translateTitle('Ve.elements.分')}`
      },
      // 清空参数
      $clearFormData() {
        this.info.data.formData = {}
        // 重新调用接口
        this.requestData()
        // 停止接口调用的定时器
        if (this.interval) {
          clearInterval(this.interval)
        }
      },
    },
  })
</script>
<style lang="scss" scoped></style>
